<?php
class Movie {        

    public $id;
    public $name;
    public $path;
    public $dateLastChange;
    public $listMovieDetails;


    public function getMovieDetails(){
        $this->listMovieDetails = array();


        $query    = "SELECT * FROM movieDetail where movieId=" . $this->id . " and state = 1 ORDER BY code";
                
        $result   = mysql_query($query);
        if(mysql_num_rows($result)!=0){
            while($row = mysql_fetch_assoc($result)){                     
                $movieDetail = new MovieDetail();

                $movieDetail->code           = $row["code"];
                $movieDetail->movieId        = $row["movieId"];
                $movieDetail->title          = $row["title"];
                $movieDetail->synopsis       = $row["synopsis"];
                $movieDetail->posterURL      = $row["posterURL"];
                $movieDetail->posterURLLocal = $row["posterURLLocal"];
                $movieDetail->productionYear = $row["productionYear"];
                $movieDetail->releaseDate    = $row["releaseDate"];
                $movieDetail->directors      = $row["directors"];
                $movieDetail->actors         = $row["actors"];
                $movieDetail->pressRating    = $row["pressRating"];
                $movieDetail->userRating     = $row["userRating"];
                $movieDetail->state          = $row["state"];

                $this->listMovieDetails[]= $movieDetail;
            }
        }
    }

    
    public function save()
    {
        
        $req = "REPLACE movie SET ";
        
        if($this->id != null){
            $req .=" id   =".$this->id.",";
        }   

        $req .= "
            name ='".$this->name."',
            path ='".$this->path."',
            dateLastChange='".$this->dateLastChange."'
            ";
            
        $result = mysql_query($req);
        
        if($this->id == null){

            $query    = "select id from movie where name='".$this->name."' limit 1";
        
            $result   = mysql_query($query);
            // Recuperation des resultats            
            if(mysql_num_rows($result)!=0){
                $row = mysql_fetch_assoc($result);
                
                $this->id = $row["id"];
                
            }
        }

        return $result;
    }


    //----------------------//
    //--------STATIC--------//
    //----------------------//

    public static function restorOrCreateMovieByName($name)
    {
        $movie = new Movie();

        $query = "SELECT * FROM movie where name='".$name."' LIMIT 1";

        $result = mysql_query($query);
               
        if(mysql_num_rows($result)!=0){
            $row = mysql_fetch_assoc($result);

            $movie->id             = $row["id"];
            $movie->name           = $row["name"];
            $movie->path           = $row["path"];
            $movie->dateLastChange = $row["dateLastChange"];

        }else{
            $movie->name = $name;
        }

        return $movie;
    }

    public static function isNewMovie($name)
    {
        $return = false;

        $query = "SELECT * FROM movie where name='".self::cleanMovieName($name)."' LIMIT 1";

        $result = mysql_query($query);
               
        if(mysql_num_rows($result)==0){
            $return = true;
        }

        return $return;
    }

     public static function getMovieByPath($path, $name)
    {
        try {
            $movie = self::restorOrCreateMovieByName(self::cleanMovieName($name));
            
            $movie->path           = str_replace("'","\\'",str_replace(DIRECTORY_SEPARATOR, DS, $path). DS . $name);
            $movie->dateLastChange = date("Y-m-d H:i", filectime($path . DS . $name));            
            
            $movie->save();

        } catch (Exception $e) {
            // Afficher un message d'erreur.
            echo "Erreur " . $e->getCode() . ": " . $e->getMessage();            
        }
        return $movie;
    }

    public static function getListMovieFromFolders($onlyNewMovie = false)
    {
        $listMovie      = array();
        $istMovieFolder = self::getListMovieFolder();
        
        foreach ($istMovieFolder as $path) {
            try {
                //premier niveau
                $dir = opendir($path);
                
                while ($file = readdir($dir)) {                                            
                    if ($file != '.' && $file != '..' && !is_dir($path . DS . $file)&&((strpos($file,".avi"))||(strpos($file,".mkv")))&&(!$onlyNewMovie || self::isNewMovie($file))) {                
                        $listMovie[] = self::getMovieByPath($path,$file);
                    }
                    //deuxieme niveau
                    if ($file != '.' && $file != '..' && is_dir($path . DS . $file)) {
                        $dir2 = opendir($path . DS . $file);
                        while ($file2 = readdir($dir2)) {
                            if ($file2 != '.' && $file2 != '..' && !is_dir($path . DS . $file . DS . $file2)&&((strpos($file,".avi"))||(strpos($file,".mkv")))&&(!$onlyNewMovie || self::isNewMovie($file2))) {
                                $listMovie[] = self::getMovieByPath($path . DS . $file,$file2);
                            }
                        }
                    }
                }                
            } catch (Exception $e) {
                // Afficher un message d'erreur.
                echo "Erreur " . $e->getCode() . ": " . $e->getMessage();
            }
        }        
        return $listMovie;
    }

     public static function getListMovie($filter = null, $debug= false)
    {
        $listMovie = array();

        $query    = "SELECT * FROM movie order by dateLastChange DESC";

        if($filter!=null){
            $query .= " where ".$filter;
        }

        if($debug){
            $query .= " limit 0,10";
        }

        $result   = mysql_query($query);

        if(mysql_num_rows($result)!=0){
            while($row = mysql_fetch_assoc($result)){   
                $movie = new Movie();

                $movie->id             = $row["id"];
                $movie->name           = $row["name"];
                $movie->path           = $row["path"];
                $movie->dateLastChange = $row["dateLastChange"];      

                $listMovie[] = $movie;
            }
        }

        return $listMovie;
    }

    public static function getListMovieFolder()
    {
        $listMovieFolder = array();

        $query    = "SELECT value,Id FROM param where name='path' ORDER BY name";
        
        $result   = mysql_query($query);
        // Recuperation des resultats
        $tab_film = array();
        if(mysql_num_rows($result)!=0){
            while($row = mysql_fetch_assoc($result)){                     
                $listMovieFolder[] = $row["value"];
            }
        }

        return $listMovieFolder;
    }

    public static function cleanMovieName($path)
    {
        $pathCleaned = strtolower($path);
        $pathCleaned = str_replace('.avi', '', $pathCleaned);
        $pathCleaned = str_replace('.mkv', '', $pathCleaned);
        $pathCleaned = str_replace('.', ' ', $pathCleaned);
        $pathCleaned = str_replace('-', ' ', $pathCleaned);
        $pathCleaned = str_replace('_', ' ', $pathCleaned);
        $pathCleaned = str_replace("'", ' ', $pathCleaned);             

        return $pathCleaned;
    }
}

